# -*- coding: utf-8-*-
from openerp.osv import osv, fields
from openerp import SUPERUSER_ID
from menu import WXMenu


# 微信企业号菜单
class wechat_agent_menu(osv.osv):
    _name = 'wechat.agent.menu'
    _description = u"微信菜单"

    MENU_TYPE = [
        ('click', u'菜单Key'),
        ('view', u'跳转到网页'),
        ('scancode_push', u'扫描推事件'),
        ('scancode_waitmsg', u'扫描推事件（弹框）'),
        ('pic_sysphoto', u'系统拍照'),
        ('pic_photo_or_album', u'拍照或相册'),
        ('pic_weixin', u'微信发图器'),
        ('location_select', u'地理位置选择器'),
    ]

    def gather_menu_vals(self, cr, uid, ids, context=None):
        res, agent_ids = {}, set()
        for menu in self.browse(cr, uid, ids, context=context):
            if menu.menu_level == 'first' and menu.id not in res:
                menu_val = {'name': menu.name}
                if not menu.child_menu_ids:
                    if menu.type == 'view':
                        menu_val.update({'type': 'view', 'url': menu.url})
                    else:
                        menu_val.update({'type': menu.type, 'key': menu.key})
                else:
                    menu_val.update({'sub_button': []})

                res.update({menu.id: menu_val})
            else:
                menu_val = {'name': menu.name, 'type': menu.type}
                if menu.type == 'view':
                    menu_val.update({'url': menu.url})
                else:
                    menu_val.update({'key': menu.key})

                if menu.parent_menu_id.id in res:
                    res[menu.parent_menu_id.id]['sub_button'].append(menu_val)
                else:
                    res.update({
                            menu.parent_menu_id.id: {
                                'name': menu.parent_menu_id.name,
                                'sub_button': [menu_val],
                            }
                        })
            agent_ids.add(menu.agent_id.id)

        if len(agent_ids) != 1:
            raise osv.except_osv(u'错误', u'只能选择同时同步同一个应用的菜单')

        return agent_ids.pop(), {'button': res.values()}

    def sync_menu(self, cr, uid, agent_id, vals, context=None):
        application_id, access_token = self.get_access_token(cr, uid, agent_id, context=context)
        WXMenu.create(access_token, application_id, vals=vals)

    def get_access_token(self, cr, uid, agent_id, context=None):
        if agent_id:
            agent = self.pool.get('wechat.application').browse(cr, uid, agent_id, context=context)
            if agent.permission_group_ids and agent.permission_group_ids[0].access_token:
                return agent.application_id, agent.permission_group_ids[0].access_token

        return self._get_agentid(cr, uid, context=context), self._get_access_token(cr, uid, context=context)

    def _get_agentid(self, cr, uid, context=None):
        ir_model_data = self.pool.get('ir.model.data')
        wechat_application = self.pool.get('wechat.application')

        application_id = ir_model_data.xmlid_to_res_id(cr, 1, 'dftg_weixin.weixin_dftg_test_application')
        application = wechat_application.browse(cr, SUPERUSER_ID, application_id, context=context)

        if not application or not application.application_id:
            raise osv.except_osv(u'错误', u'无法获取到应用的agent_id')

        return application.application_id

    def _get_access_token(self, cr, uid, context=None):
        ir_model_data = self.pool.get('ir.model.data')
        wechat_enterprise = self.pool.get('wechat.enterprise')

        enterprise_id = ir_model_data.xmlid_to_res_id(cr, 1, 'dftg_weixin.weixin_dftg_enterprise')
        enterprise = wechat_enterprise.browse(cr, SUPERUSER_ID, enterprise_id, context=context)

        if not enterprise or not enterprise.access_token:
            raise osv.except_osv(u'错误', u'无法获取到微信企业号的access_token')

        return enterprise.access_token

    _columns = {
        'type': fields.selection(MENU_TYPE, string=u'类型'),
        'name': fields.char(u'菜单标题'),
        'key': fields.char(u'菜单Key值'),
        'url': fields.char(u'网页链接'),
        'menu_level': fields.selection([('first', u'一级菜单'), ('second', u'二级菜单')], string=u'菜单等级'),
        'has_sub_menu': fields.boolean(u'存在子菜单'),
        'parent_menu_id': fields.many2one('wechat.agent.menu', u'上级菜单'),
        'child_menu_ids': fields.one2many('wechat.agent.menu', 'parent_menu_id', u'子菜单'),
        'synced': fields.boolean(u'已同步', copy=False),
        'agent_id': fields.many2one('wechat.application', u'微信应用'),
    }

    _defaults = {
        'type': 'view',
        'menu_level': 'first',
        'agent_id': lambda self, cr, uid, ctx=None: ctx.get('active_id'),
    }
